package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.LoveMusicDao;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/loveMusicServlet")
//添加音乐到喜欢的列表
public class LoveMusicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        Map<String,Object> return_map = new HashMap<>();
        String musicIds = req.getParameter("id");
        int musicId = Integer.parseInt(musicIds);
        User user = (User) req.getSession().getAttribute("user");
        int userId = user.getId();
        LoveMusicDao loveMusicDao = new LoveMusicDao();
        boolean effect2 = loveMusicDao.findLoveMusicByMusicIdAndUserId(userId,musicId);
        if (effect2){
            return_map.put("msg",false);
        }else {
            boolean effect = loveMusicDao.insertLoveMusic(userId,musicId);
            if (effect){
                return_map.put("msg",true);
            }else {
                return_map.put("msg",false);
            }
        }


        ObjectMapper mapper = new ObjectMapper();
        //利用Jackson将map转化为json对象，
        // writer 将转换后的json字符串保存到字符输出流中，最后给客户端
        mapper.writeValue(resp.getWriter(),return_map);
    }
}
